{
 "cells": [
  {
   "cell_type": "code",
   "execution_count": null,
   "id": "initial_id",
   "metadata": {
    "collapsed": true
   },
   "outputs": [],
   "source": [
    ""
   ]
  },
  {
   "metadata": {
    "ExecuteTime": {
     "end_time": "2025-07-03T15:13:18.981955Z",
     "start_time": "2025-07-03T15:13:18.925757Z"
    }
   },
   "cell_type": "code",
   "source": [
    "import numpy as np\n",
    "\n",
    "# 定义原始数据集\n",
    "data = {\n",
    "    '姓名': ['张三', '李四', '王五', '赵六'],\n",
    "    'X1_年龄': [25, 36, 45, 55],\n",
    "    'X2_收入': [10000, 50000, 80000, 100000]\n",
    "}\n",
    "\n",
    "# 提取特征矩阵（n_samples, n_features）\n",
    "X = np.array([data['X1_年龄'], data['X2_收入']]).T  # 形状为(4, 2)\n",
    "\n",
    "\n",
    "# 定义标准归一化函数\n",
    "def standardization(X):\n",
    "    \"\"\"\n",
    "    对特征矩阵进行标准归一化（Z-Score标准化）\n",
    "\n",
    "    参数：\n",
    "    X: 原始特征矩阵 (n_samples, n_features)\n",
    "\n",
    "    返回：\n",
    "    X_standardized: 标准化后的特征矩阵\n",
    "    feature_stats: 包含各特征均值和标准差的字典\n",
    "    \"\"\"\n",
    "    n_features = X.shape[1]\n",
    "    X_standardized = X.copy().astype(np.float64)\n",
    "    feature_stats = {'mean': [], 'std': []}\n",
    "\n",
    "    for i in range(n_features):\n",
    "        mu = np.mean(X[:, i])  # 计算第i列均值\n",
    "        sigma = np.std(X[:, i])  # 计算第i列标准差（无偏估计可选ddof=1，此处用总体标准差）\n",
    "        X_standardized[:, i] = (X_standardized[:, i] - mu) / sigma\n",
    "        feature_stats['mean'].append(mu)\n",
    "        feature_stats['std'].append(sigma)\n",
    "\n",
    "    return X_standardized, feature_stats\n",
    "\n",
    "\n",
    "# 应用标准归一化\n",
    "X_standardized, stats = standardization(X)\n",
    "\n",
    "# 输出结果\n",
    "print(\"原始特征矩阵：\")\n",
    "print(\"年龄：\", data['X1_年龄'])\n",
    "print(\"收入：\", data['X2_收入'], \"\\n\")\n",
    "\n",
    "print(\"各特征均值：\", stats['mean'])  # 年龄均值40.25，收入均值60000\n",
    "print(\"各特征标准差：\", stats['std'], \"\\n\")  # 年龄标准差≈11.08，收入标准差≈33911.64\n",
    "\n",
    "print(\"标准归一化后特征矩阵（均值0，标准差1）：\")\n",
    "print(\"年龄归一化：\", np.round(X_standardized[:, 0], 4))  # 张三年龄≈-1.3763\n",
    "print(\"收入归一化：\", np.round(X_standardized[:, 1], 4))  # 张三收入≈-1.4743"
   ],
   "id": "8c1104ca2dd9e7f0",
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "原始特征矩阵：\n",
      "年龄： [25, 36, 45, 55]\n",
      "收入： [10000, 50000, 80000, 100000] \n",
      "\n",
      "各特征均值： [40.25, 60000.0]\n",
      "各特征标准差： [11.07643895843786, 33911.64991562634] \n",
      "\n",
      "标准归一化后特征矩阵（均值0，标准差1）：\n",
      "年龄归一化： [-1.3768 -0.3837  0.4288  1.3317]\n",
      "收入归一化： [-1.4744 -0.2949  0.5898  1.1795]\n"
     ]
    }
   ],
   "execution_count": 1
  },
  {
   "metadata": {
    "ExecuteTime": {
     "end_time": "2025-07-03T16:17:49.134172Z",
     "start_time": "2025-07-03T16:17:49.113907Z"
    }
   },
   "cell_type": "code",
   "source": [
    "from sklearn.preprocessing import StandardScaler\n",
    "import numpy as np\n",
    "\n",
    "# 定义原始数据集（同前文年龄与收入案例）\n",
    "data = {\n",
    "    'X1_年龄': [25, 36, 45, 55],\n",
    "    'X2_收入': [10000, 50000, 80000, 100000]\n",
    "}\n",
    "X = np.array([data['X1_年龄'], data['X2_收入']]).T  # 形状为(4, 2)\n",
    "\n",
    "# 1. 创建标准归一化器\n",
    "scaler = StandardScaler()  # 自动计算均值和标准差，输出均值0、标准差1的数据\n",
    "\n",
    "# 2. 在训练集上拟合并转换（核心步骤：计算均值μ和标准差σ）\n",
    "X_standardized = scaler.fit_transform(X)\n",
    "\n",
    "# 3. 查看统计量（训练集的均值和标准差）\n",
    "print(\"特征1（年龄）均值μ =\", np.round(scaler.mean_[0], 4))  # 40.25\n",
    "print(\"特征1（年龄）标准差σ =\", np.round(scaler.scale_[0], 4))  # 11.0803\n",
    "print(\"特征2（收入）均值μ =\", scaler.mean_[1])  # 60000.0\n",
    "print(\"特征2（收入）标准差σ =\", np.round(scaler.scale_[1], 4))  # 33911.6441\n",
    "\n",
    "# 4. 输出归一化结果（与前文手动计算一致）\n",
    "print(\"\\n标准归一化后特征矩阵：\")\n",
    "print(\"张三（25, 10000）：\", np.round(X_standardized[0], 4))  # [-1.3763 -1.4743]\n",
    "print(\"李四（36, 50000）：\", np.round(X_standardized[1], 4))  # [-0.3833 -0.295 ]\n",
    "print(\"王五（45, 80000）：\", np.round(X_standardized[2], 4))  # [ 0.4287  0.5897]\n",
    "print(\"赵六（55, 100000）：\", np.round(X_standardized[3], 4))  # [ 1.3312  1.1789]"
   ],
   "id": "2cbfa5ef6e7148ae",
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "特征1（年龄）均值μ = 40.25\n",
      "特征1（年龄）标准差σ = 11.0764\n",
      "特征2（收入）均值μ = 60000.0\n",
      "特征2（收入）标准差σ = 33911.6499\n",
      "\n",
      "标准归一化后特征矩阵：\n",
      "张三（25, 10000）： [-1.3768 -1.4744]\n",
      "李四（36, 50000）： [-0.3837 -0.2949]\n",
      "王五（45, 80000）： [0.4288 0.5898]\n",
      "赵六（55, 100000）： [1.3317 1.1795]\n"
     ]
    }
   ],
   "execution_count": 5
  },
  {
   "metadata": {},
   "cell_type": "code",
   "outputs": [],
   "execution_count": null,
   "source": "",
   "id": "85b64ef52376df44"
  }
 ],
 "metadata": {
  "kernelspec": {
   "display_name": "Python 3",
   "language": "python",
   "name": "python3"
  },
  "language_info": {
   "codemirror_mode": {
    "name": "ipython",
    "version": 2
   },
   "file_extension": ".py",
   "mimetype": "text/x-python",
   "name": "python",
   "nbconvert_exporter": "python",
   "pygments_lexer": "ipython2",
   "version": "2.7.6"
  }
 },
 "nbformat": 4,
 "nbformat_minor": 5
}
